/**
 * 
 */
package com.hm.uums;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hm.common.Constant;
import com.hm.common.api.ApiResult;
import com.hm.common.api.ApiStatus;
import com.hm.common.exception.NoAuthException;

/**
 * 统一异常处理
 * 
 * @author hwg
 *
 *         2020年12月18日
 */
@ControllerAdvice
public class ExceptionHandler {
	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

	@org.springframework.web.bind.annotation.ExceptionHandler
	@ResponseBody
	public ApiResult<String> exceptionHandler(Exception e, HttpServletResponse response, HttpServletRequest request) {
		logger.error("统一异常处理", e);
		String reqId = request.getHeader(Constant.REQUEST_ID);
		if (e instanceof HttpRequestMethodNotSupportedException) {
			response.setStatus(405);
			return ApiResult.of(reqId, ApiStatus.STATUS_405, e.getMessage(), request.getRequestURI(), null);
		}
		if (e instanceof NoAuthException) {
			response.setStatus(403);
			return ApiResult.of(reqId, ApiStatus.STATUS_403, request.getRequestURI());
		}
		
		if (e instanceof NullPointerException) {
			response.setStatus(500);
			return ApiResult.of(reqId, ApiStatus.STATUS_999, "空指针异常", request.getRequestURI(), null);
		}
		
		response.setStatus(500);
		return ApiResult.of(reqId, ApiStatus.STATUS_999, e.getMessage(), request.getRequestURI(), null);
	}
}
